Walkthrough 11-8: Use DataWeave functions
In this walkthrough, you continue to work with the flights JSON posted to the flow. You will:
· Use functions in the Core module that are imported automatically.
· Replace data values using pattern matching.
· Order data, remove duplicate data, and filter data.
· Use a function in another module that you must explicitly import into a script to use.
· Dasherize data.
Starting file
If you did not complete the previous walkthrough, you can get a starting file here. This file is also located in the solutions folder of the student files ZIP located in the Course Resources.
Use the replace function
1. Return to the Transform Message properties view for the transformation in postMultipleFlights.
2. Change the output type from application/java to application/dw.
3. Look at the preview and see that Boeing is misspelled.
4. For planeType, use the replace function to replace the string Boing with Boeing.
planeType: upper(replace(object.planeType,/(Boing)/) with "Boeing"),
5. Look at the preview; Boeing should now be spelled correctly.
Use the dasherize function in the Strings module
6. For planeType, replace the upper function with the dasherize function.
planeType: dasherize(replace(object.planeType,/(Boing)/) with "Boeing"),
7. Look at the error you get.
8. In the script header, add an import statement to import dasherize from the Strings module.
import dasherize from dw::core::Strings
9. Look at the preview.
Use the orderBy function
10. In the preview section, look at the flight prices; the flights are not ordered by price.
11. Use the orderBy function to order the flights object by price.
flights orderBy $.price
12. Look at the preview; the flights should now be ordered by price.
13. Look at the three $283 flights; there is a duplicate and they are not ordered by date.
14. Change the DataWeave expression to sort flights by date and then by price.
flights orderBy $.departureDate
orderBy $.price
15. Look at the preview; the flights should now be ordered by price and flights of the same price should be sorted by date.
Remove duplicate data
16. Use the distinctBy function to first remove any duplicate objects.
flights distinctBy $
orderBy $.departureDate
orderBy $.price
17. Look at the preview; you should now see only two $283 flights to PDX instead of three.
18. Add an availableSeats field that is equal to the emptySeats field and coerce it to a number.
availableSeats: object.emptySeats as Number
19. Look at the preview; you should get three $283 flights to PDX again.
Use the filter function
20. In the preview, look at the values of the availableSeats properties; you should see one is equal to zero.
21. Use the filter function to remove any objects that have availableSeats equal to 0.
flights distinctBy $
filter ($.availableSeats !=0)
orderBy $.departureDate
orderBy $.price
22. Look at the preview; you should no longer get the flight that had no available seats.